package com.uplooking.util;

import android.graphics.Bitmap;
import android.graphics.Bitmap.Config;
import android.graphics.Canvas;
import android.graphics.LinearGradient;
import android.graphics.Matrix;
import android.graphics.Paint;
import android.graphics.PorterDuffXfermode;
import android.graphics.Shader.TileMode;

public class BitmapUtil {
	/**
	 * 获得图片的倒影
	 * @param srcBitmap 原始图片
	 * @return 加上倒影后的图片
	 */
	public static Bitmap createReflectedBitmap(Bitmap srcBitmap) {
		if (null == srcBitmap) {
			return null;
		}

		// 倒影和原图之间的间隔
		final int REFLECTION_GAP = 4;

		int srcWidth = srcBitmap.getWidth();
		int srcHeight = srcBitmap.getHeight();
		int reflectionWidth = srcBitmap.getWidth();
		int reflectionHeight = srcBitmap.getHeight() / 2;

		if (0 == srcWidth || srcHeight == 0) {
			return null;
		}

		// 生成倒影的矩阵，y轴缩到-1图片刚好垂直倒置
		Matrix matrix = new Matrix();
		matrix.preScale(1, -1);

		try {
			// 倒影图片，宽度和原始图片相同，高度为原始图片的一半
			Bitmap reflectionBitmap = Bitmap.createBitmap(srcBitmap, 0, srcHeight / 2, srcWidth,
					srcHeight / 2, matrix, false);

			if (null == reflectionBitmap) {
				return null;
			}

			// 创建合成的图片 宽为图片的宽，高为两张图片加间距
			Bitmap bitmapWithReflection = Bitmap.createBitmap(reflectionWidth, srcHeight
					+ reflectionHeight + REFLECTION_GAP, Config.ARGB_8888);

			if (null == bitmapWithReflection) {
				return null;
			}

			// 准备画布
			Canvas canvas = new Canvas(bitmapWithReflection);

			// 先画原图
			canvas.drawBitmap(srcBitmap, 0, 0, null);

			// 再画倒影图
			canvas.drawBitmap(reflectionBitmap, 0, srcHeight + REFLECTION_GAP, null);

			Paint paint = new Paint();
			paint.setAntiAlias(true);
			LinearGradient shader = new LinearGradient(0, srcHeight, 0,
					bitmapWithReflection.getHeight() + REFLECTION_GAP, 0x70FFFFFF, 0x00FFFFFF,
					TileMode.MIRROR);
			paint.setShader(shader);
			paint.setXfermode(new PorterDuffXfermode(android.graphics.PorterDuff.Mode.DST_IN));

			// Draw the linear shader.
			canvas.drawRect(0, srcHeight, srcWidth, bitmapWithReflection.getHeight()
					+ REFLECTION_GAP, paint);

			return bitmapWithReflection;
		} catch (Exception e) {
			e.printStackTrace();
		}

		return null;
	}
}
